package weather

import (
	"time"

	"github.com/ziutek/mymysql/mysql"
	_ "github.com/ziutek/mymysql/native" // Native engine
	// _ "github.com/ziutek/mymysql/thrsafe" // Thread safe engine
)

type WeatherDB struct {
	db mysql.Conn
}

func (WeatherDBcell *WeatherDB) Init() error {
	WeatherDBcell.db = mysql.New("tcp", "", ConfigCell.WaetherDBIP, ConfigCell.WaetherDBUser, ConfigCell.WaetherDBPassword, ConfigCell.WaetherDBDBName)
	return WeatherDBcell.db.Connect()
}

func (WeatherDBcell *WeatherDB) GetWeather(location string) (string, error) {
	var rv string
	var err error
	// 判断是否连接
	if WeatherDBcell.db == nil || !WeatherDBcell.db.IsConnected() {
		// 没连接则连接
		err := WeatherDBcell.Init()
		// 连接失败则返回
		if err != nil {
			LogFile.Println("数据库连接失败")
			LogFile.Println(err)
			return "", err
		}
	}

	// 查询
	SQL := "select * from weather where location='" + location + "'"
	rows, res, err := WeatherDBcell.db.Query(SQL)
	if err != nil {
		LogFile.Println("数据库查询失败，尝试重新连接")
		LogFile.Println(err)
		// 重新连接
		err = WeatherDBcell.db.Reconnect()
		if err != nil {
			LogFile.Println("尝试重新连接失败")
			LogFile.Println(err)
			return "", err
		}

		rows, res, err = WeatherDBcell.db.Query(SQL)
		if err != nil {
			LogFile.Println("重新连接后查询还是失败")
			LogFile.Println(err)
			return "", err
		}
	}

	// 如果没数据说明是第一次
	if len(rows) == 0 {
		// 获取数据
		rv, err = WeatherApi_GetWeather(location)
		if err == nil {
			// 更新数据
			stmt, err1 := WeatherDBcell.db.Prepare("insert into weather values(null, ?, ?, ?)")
			if err1 == nil {
				_, err1 := stmt.Run(location, rv, time.Now().Format("2006-01-02 15:04:05"))
				if err1 != nil {
					LogFile.Println("数据库插入失败")
					LogFile.Println(err)
				}
			} else {
				LogFile.Println("数据库插入失败")
				LogFile.Println(err)
			}
		}
		return rv, err
	}

	for _, row := range rows {
		//  获取属性对应的索引
		weather := res.Map("weather")
		updatetime := res.Map("updatetime")

		// 获取数据
		rv = row.Str(weather)
		Date := row.Str(updatetime)

		// 解析时间
		tm, _ := time.Parse("2006-01-02 15:04:05", Date)

		// 判断是否是超两小事了超过了就刷新了
		bef, _ := time.ParseDuration("-2h")
		two2hbef := time.Now().Add(bef)
		if tm.Before(two2hbef) {
			// 两小时前的数据
			rv, err = WeatherApi_GetWeather(location)
			if err == nil {
				// 更新数据
				stmt, err1 := WeatherDBcell.db.Prepare("UPDATE weather SET weather=?,updatetime=? WHERE location=?")
				if err1 == nil {
					_, err1 := stmt.Run(rv, time.Now().Format("2006-01-02 15:04:05"), location)
					if err1 != nil {
						LogFile.Println("数据库插入失败")
						LogFile.Println(err)
					}
				} else {
					LogFile.Println("数据库插入失败")
					LogFile.Println(err)
				}
			}
		}
	}

	return rv, err
}
